﻿using DB;
using Newtonsoft.Json;
using OMSBlackTechnology.Common;
using OMSBlackTechnology.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace OMSBlackTechnology.Controllers
{
    /// <summary>
    /// 库存
    /// </summary>
    public class StockController : Controller
    {

        //同步库存接口地址
        private readonly string URL = "api/Inventory/InventoryPush";

        //商品个数
        private readonly int SEND_COUNT = 10;

        // GET: Stock
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult IdSync()
        {
            return View();
        }

        public ActionResult VendorSync()
        {
            return View();
        }

        [HttpPost]
        public ActionResult IdSync(IdSyncModel model)
        {
            if (string.IsNullOrWhiteSpace(model.ProductIds))
            {
                TempData["Message"] = "提交要同步的数据";
                return View();
            }



            //分隔符
            var separator = new char[] { ';' };

            var productIds = model.ProductIds.Split(separator, StringSplitOptions.RemoveEmptyEntries);


            var relativePath = "/StorePushInfo/";
            var Path = HttpContext.Server.MapPath(@"~" + relativePath);

            if (!Directory.Exists(Path))
                Directory.CreateDirectory(Path);
            var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".html";
            Path = Path + fileName;
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("<!DOCTYPE html><html><head><meta charset =\"utf-8\" ><title></title> <link href=\"../Content/bootstrap.css\" rel=\"stylesheet\" /><link href = \"../Content/bootstrap-theme.min.css\" rel = \"stylesheet\" /><link href = \"../Content/bootstrap-table/bootstrap-table.min.css\" rel = \"stylesheet\" /><script type = \"text/javascript\" src = \"../Scripts/jquery-3.3.1.min.js\" ></script><script type = \"text/javascript\" src = \"../Scripts/bootstrap.min.js\" ></script><script type = \"text/javascript\" src = \"../Content/bootstrap-table/bootstrap-table.min.js\" ></script></head><body><table class=\"table table-bordered table-hover\"><thead><tr><th>商品Id</th><th>Sku</th><th>店铺Id</th><th>仓库Id</th><th>数量</th><th>时间</th><th>状态</th><th>消息</th></tr><thead><tbody>");
            SyncStock(productIds, stringBuilder);
            if (TempData["Message"] != null)
            {
                return View();
            }
            stringBuilder.Append("</tbody></table></body></html> ");

            if (!System.IO.File.Exists(Path))
            {
                System.IO.FileStream f = System.IO.File.Create(Path);
                f.Close();
                f.Dispose();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(Path, true, System.Text.Encoding.UTF8);
            f2.WriteLine(stringBuilder.ToString());
            f2.Close();
            f2.Dispose();
            //FileInfo fileInfo=new FileInfo()

            return Redirect(relativePath + fileName);
        }

        [HttpPost]
        public ActionResult VendorSync(IdSyncModel model)
        {
            if (string.IsNullOrWhiteSpace(model.VendorIds))
            {
                TempData["Message"] = "提交要同步的数据";
                return View();
            }



            //分隔符
            var separator = new char[] { ';' };

            List<StoreDetail> storeDetailList = new List<StoreDetail>();

            var vendorArray = model.VendorIds.Split(separator, StringSplitOptions.RemoveEmptyEntries);

            List<int> vendorIds = new List<int>();

            foreach (var item in vendorArray)
            {
                vendorIds.Add(Convert.ToInt32(item));
            }

            vendorIds = vendorIds.Distinct().ToList();

            var storeDetailIds = new List<string>();

            using (nopdbEntities ent = new nopdbEntities())
            {
                storeDetailList = (from f in ent.StoreDetail where vendorIds.Contains(f.VendorId) select f).ToList();
                //storeDetailList = (from f in ent.StoreDetail where vendorIds.Contains(f.VendorId) select f).ToList();
                storeDetailIds = storeDetailList.Select(p => p.Id.ToString()).ToList();
            }

            var productIds = storeDetailList.Select(p => p.ProductId.ToString()).Distinct().ToArray();


            var relativePath = "/StorePushInfo/";
            var Path = HttpContext.Server.MapPath(@"~" + relativePath);

            if (!Directory.Exists(Path))
                Directory.CreateDirectory(Path);
            var fileDate = DateTime.Now.ToString("yyyyMMddHHmmss");
            var fileName = fileDate + ".html";
            var fullPath = Path + fileName;
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("<!DOCTYPE html><html><head><meta charset =\"utf-8\" ><title></title> <link href=\"../Content/bootstrap.css\" rel=\"stylesheet\" /><link href = \"../Content/bootstrap-theme.min.css\" rel = \"stylesheet\" /><link href = \"../Content/bootstrap-table/bootstrap-table.min.css\" rel = \"stylesheet\" /><script type = \"text/javascript\" src = \"../Scripts/jquery-3.3.1.min.js\" ></script><script type = \"text/javascript\" src = \"../Scripts/bootstrap.min.js\" ></script><script type = \"text/javascript\" src = \"../Content/bootstrap-table/bootstrap-table.min.js\" ></script></head><body><table class=\"table table-bordered table-hover\"><thead><tr><th>商品Id</th><th>Sku</th><th>店铺Id</th><th>仓库Id</th><th>数量</th><th>时间</th><th>状态</th><th>消息</th></tr><thead><tbody>");
            SyncStock(productIds, stringBuilder);
            if (TempData["Message"] != null)
            {
                return View();
            }
            stringBuilder.Append("</tbody></table></body></html> ");

            if (!System.IO.File.Exists(fullPath))
            {
                System.IO.FileStream f = System.IO.File.Create(fullPath);
                f.Close();
                f.Dispose();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(fullPath, true, System.Text.Encoding.UTF8);
            f2.WriteLine(stringBuilder.ToString());
            f2.Close();
            f2.Dispose();
            //FileInfo fileInfo=new FileInfo()


            if (storeDetailIds != null && storeDetailIds.Count > 0)
            {
                var txtPath = Path + fileDate + ".txt";
                if (!System.IO.File.Exists(txtPath))
                {
                    System.IO.FileStream f = System.IO.File.Create(txtPath);
                    f.Close();
                    f.Dispose();
                }

                System.IO.StreamWriter txtSW = new System.IO.StreamWriter(txtPath, true, System.Text.Encoding.UTF8);
                txtSW.WriteLine(string.Join(",", storeDetailIds.ToArray()));
                txtSW.Close();
                txtSW.Dispose();

            }


            return Redirect(relativePath + fileName);
        }

        public void SyncStock(string[] ids, StringBuilder message)
        {

            List<StorePushModel> storePushList = new List<StorePushModel>();
            int Counter = 1; //计数器

            //基础数据
            List<Vendor_Store_Mapping> vendorStoreGB = new List<Vendor_Store_Mapping>();
            List<PlatformStore> platformStoreList = new List<PlatformStore>();

            List<Warehouse> warehouseList = new List<Warehouse>();

            using (nopdbEntities ent = new nopdbEntities())
            {
                var vendorStoreList = (from f in ent.Vendor_Store_Mapping where !f.Deleted select f).ToList();

                vendorStoreGB = vendorStoreList.GroupBy(g => new
                {
                    g.VendorId,
                    g.StoreId
                }).Select(s => new Vendor_Store_Mapping
                {
                    VendorId = s.Key.VendorId,
                    StoreId = s.Key.StoreId
                }).OrderBy(o => o.StoreId).ToList();


                bool? isDelete = false;
                platformStoreList = (from f in ent.PlatformStore where f.Deleted == isDelete select f).ToList();

                warehouseList = (from f in ent.Warehouse select f).ToList();
            }

            foreach (var item in ids)
            {
                int id = 0;
                int.TryParse(item, out id);

                if (id == 0)
                {
                    SetMessage(item, string.Empty, 0, 0, 0, "未推送", "商品Id格式不正确", message);
                }
                else
                {

                    using (nopdbEntities ent = new nopdbEntities())
                    {
                        Product product = (from c in ent.Product where c.Id == id select c).FirstOrDefault();
                        if (product == null || product.Id == 0)
                        {
                            SetMessage(item, string.Empty, 0, 0, 0, "未推送", "未查找到对应商品", message);
                        }
                        else if (product.Deleted)
                        {
                            SetMessage(item, string.Empty, 0, 0, 0, "未推送", "商品已经删除", message);
                        }
                        else
                        {
                            var combinationList = product.ProductAttributeCombination.OrderBy(o => o.Sku).ToList();
                            int combinationCount = combinationList.Count;
                            if (combinationCount == 0)
                            {
                                SetMessage(item, string.Empty, 0, 0, 0, "未推送", "未查找到商品对应的Sku", message);
                            }
                            else
                            {
                                var storeDetailList = (from f in ent.StoreDetail where f.ProductId == id select f).ToList();

                                var stockFreezeList = (from f in ent.StockFreeze where f.ProductId == id && f.IsDelete == 0 select f).ToList();

                                //库存分组
                                var storeDetailGB = storeDetailList.GroupBy(g => new
                                {
                                    g.AvailableQuantity,
                                    g.Id,
                                    g.ProductId,
                                    g.Sku,
                                    g.VendorId,
                                    g.WarehouseId,
                                    g.IsEnabled,
                                }).Select(s => new StoreDetail
                                {
                                    AvailableQuantity = s.Sum(p => p.AvailableQuantity),
                                    Id = s.Max(p => p.Id),
                                    ProductId = s.Key.ProductId,
                                    Sku = s.Key.Sku,
                                    VendorId = s.Key.VendorId,
                                    WarehouseId = s.Key.WarehouseId,
                                    IsEnabled = s.Key.IsEnabled
                                }).ToList();

                                //冻结分组
                                var stockFreezeGB = stockFreezeList.GroupBy(g => new
                                {
                                    g.FreezeNum,
                                    g.ProductId,
                                    g.Sku,
                                    g.VendorId,
                                    g.WarehouseId
                                }).Select(s => new StockFreeze
                                {
                                    FreezeNum = s.Sum(p => p.FreezeNum),
                                    ProductId = s.Key.ProductId,
                                    Sku = s.Key.Sku,
                                    VendorId = s.Key.VendorId,
                                    WarehouseId = s.Key.WarehouseId
                                }).ToList();

                                //库存-冻结
                                foreach (var store in storeDetailGB)
                                {
                                    var stockFreeze = stockFreezeGB.Where(p => p.ProductId == store.ProductId && p.Sku == store.Sku && p.VendorId == store.VendorId && p.WarehouseId == store.WarehouseId).FirstOrDefault();
                                    if (stockFreeze != null)
                                    {
                                        if (!store.IsEnabled)
                                        {
                                            store.AvailableQuantity = 0;
                                        }
                                        else
                                        {
                                            store.AvailableQuantity -= stockFreeze.FreezeNum;
                                        }
                                    }
                                    else
                                    {
                                        if (!store.IsEnabled)
                                        {
                                            store.AvailableQuantity = 0;
                                        }
                                    }
                                }

                                //组合推送数据

                                foreach (var comb in combinationList)
                                {
                                    foreach (var vs in vendorStoreGB)
                                    {
                                        PlatformStore platformStore = null;
                                        if (vs.Deleted)
                                        {
                                            continue;
                                        }
                                        else
                                        {
                                            platformStore = platformStoreList.Where(p => p.id == vs.StoreId).FirstOrDefault();
                                        }

                                        if (platformStore == null)
                                        {
                                            continue;
                                        }

                                        var storeDetails = storeDetailGB.Where(p => p.Sku == comb.Sku && p.VendorId == vs.VendorId).ToList();

                                        storeDetails = storeDetails.GroupBy(g => new
                                        {
                                            g.AvailableQuantity,
                                            g.ProductId,
                                            g.Sku,
                                            g.WarehouseId
                                        }).Select(s => new StoreDetail
                                        {
                                            AvailableQuantity = s.Sum(p => p.AvailableQuantity),
                                            ProductId = s.Key.ProductId,
                                            Sku = s.Key.Sku,
                                            WarehouseId = s.Key.WarehouseId
                                        }).OrderBy(o => o.WarehouseId).ToList();

                                        foreach (var detail in storeDetails)
                                        {
                                            var warehouse = warehouseList.Where(p => p.Id == detail.WarehouseId).FirstOrDefault();
                                            StorePushModel model = new StorePushModel();
                                            model.AvailableQuantity = detail.AvailableQuantity;
                                            model.Id = Counter++;
                                            model.ProductCode = product.InternationalCode;
                                            model.ProductId = id;
                                            model.Sku = detail.Sku;
                                            model.StoreId = (int)platformStore.OutId;
                                            model.WarehouseId = detail.WarehouseId;

                                            switch (warehouse.PriceType)
                                            {
                                                case 1:
                                                    model.Price = product.HKGPrice;
                                                    break;
                                                case 2:
                                                    model.Price = product.EURPrice;
                                                    break;
                                                case 3:
                                                    model.Price = product.CHNPrice;
                                                    break;
                                                case 4:
                                                    model.Price = product.BDAPrice;
                                                    break;
                                                default:
                                                    model.Price = 0;
                                                    break;
                                            }
                                            model.Price = Math.Truncate(model.Price);

                                            storePushList.Add(model);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            var pushList = storePushList.Where(p => p.AvailableQuantity >= 0).ToList();

            List<SkuResultModel> skuResultList = new List<SkuResultModel>();

            if (pushList.Count > 0)
            {

                string resultJson = string.Empty;
                var allPage = pushList.Count() / SEND_COUNT;

                allPage += pushList.Count() / SEND_COUNT > 0 ? 1 : 0;

                if (allPage != 0)
                {
                    for (int i = 1; i <= allPage; i++)
                    {
                        var temp = pushList.Skip(SEND_COUNT * (i - 1)).Take(SEND_COUNT);

                        try
                        {
                            resultJson = Tools.HttpPost(URL, JsonConvert.SerializeObject(temp));
                        }
                        catch (Exception ex)
                        {
                            TempData["Message"] = ex.Message;
                            return;
                        }

                        skuResultList.AddRange(JsonConvert.DeserializeObject<List<SkuResultModel>>(resultJson));

                    }
                }
            }



            foreach (var push in storePushList)
            {
                if (push.AvailableQuantity < 0)
                {
                    SetMessage(push.ProductId.ToString(), push.Sku, push.StoreId, push.WarehouseId, push.AvailableQuantity, "未推送", "数量小于0", message);
                }
                else
                {
                    var result = skuResultList.Where(p => p.Id == push.Id).FirstOrDefault();
                    if (result != null)
                    {
                        SetMessage(push.ProductId.ToString(), push.Sku, push.StoreId, push.WarehouseId, push.AvailableQuantity, result.Result == 1 ? "成功" : "失败", result.Msg, message);
                    }
                    else
                    {
                        SetMessage(push.ProductId.ToString(), push.Sku, push.StoreId, push.WarehouseId, push.AvailableQuantity, "失败", "未返回数据", message);
                    }
                }
            }
        }

        public void SetMessage(string productId, string sku, int storeId, int warehouseId, decimal num, string result, string msg, StringBuilder message)
        {
            message.Append("<tr><td>" + productId + "</td><td>" + sku + "</td><td>" + storeId + "</td><td>" + warehouseId + "</td><td>" + num + "</td><td>" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "</td><td>" + result + "</td><td>" + msg + "</td></tr>");
        }
    }
}